package com.dhl.order.controller;

import com.dhl.order.client.ProductClient;
import com.dhl.order.common.ProductInfoOutput;
import com.dhl.order.dto.CartDTO;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;

@RestController
@Slf4j
public class ClientController {


    @GetMapping("/getProductMsg")
    public String msg() {
        return m4();
    }

    //第一种方式（直接写死url）
    public String m1() {
        RestTemplate restTemplate = new RestTemplate();
        String resp = restTemplate.getForObject("http://localhost:8080/msg", String.class);
        log.info("response={}", resp);
        return resp;
    }

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    //第2种方式(利用loadBalancerClient通过应用名获取url，不过需要eureka的status上显示正确的ip)
    public String m2() {

        ServiceInstance serviceInstance = loadBalancerClient.choose("PRODUCT");
        //%s看着像是占位字符，将后面的参数host与port放进去
        String url = String.format("http://%s:%s", serviceInstance.getHost(), serviceInstance.getPort()) + "/msg";
        RestTemplate restTemplate = new RestTemplate();
        String resp = restTemplate.getForObject(url, String.class);
        log.info("response={}", resp);
        return resp;
    }

    @Autowired
    private RestTemplate restTemplate;

    //第3种方式(利用loadBalancerClient注解，可以直接再resttemplate里面使用应用名字.需要注入resttemplate的bean)
    public String m3() {

        String resp = restTemplate.getForObject("http://PRODUCT/msg", String.class);
        log.info("response={}", resp);
        return resp;
    }

    @Autowired
    private ProductClient productClient;

    //使用feign(去看client包下的productclient)
    public String m4() {

        String resp = productClient.productMsg();
        log.info("response={}", resp);
        return resp;
    }


    @GetMapping("/getProductList")
    public String getProductList() {
        List<ProductInfoOutput> list = productClient.listForOrder(Arrays.asList("157875227953464068"));
        log.info("response={}", list);
        return "ok";
    }

    @GetMapping("/getProductList2")
    public String getProductList2() {
        List<ProductInfoOutput> list = productClient.listForOrder2(Arrays.asList("157875227953464068"));
        log.info("response={}", list);
        return "ok";
    }

    @GetMapping("/productDecreaseStock")
    public String productDecreaseStock() {
        productClient.decreaseStock(Arrays.asList(new CartDTO("157875227953464068", 2)));
        return "ok";
    }
}
